package com.voice.call.service.impl;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import voice.voice.call.cache.ConfigSystemCache;


import com.voice.call.common.Const;
import com.voice.call.common.ConstLang;
import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.entity.UserInfo;
import com.voice.call.entity.VosAccount;
import com.voice.call.exception.CommonException;
import com.voice.call.mapper.UserInfoMapper;
import com.voice.call.redis.RedisCacheUtil;
import com.voice.call.redis.RedisToken;
import com.voice.call.service.ConsumeLogService;
import com.voice.call.service.LoginLogService;
import com.voice.call.service.OpLogService;
import com.voice.call.service.SmsLogService;
import com.voice.call.service.SupportMccService;
import com.voice.call.service.TaskIntegralService;
import com.voice.call.service.TaskLogService;
import com.voice.call.service.UserAccountService;
import com.voice.call.service.UserInfoService;
import com.voice.call.service.VosService;
import com.voice.call.util.entity.SupportRegister;
import com.voice.call.utils.DateUtil;
import com.voice.call.utils.JSONUtil;
import com.voice.call.utils.MD5Util;
import com.voice.call.utils.StringUtil;



@Service
public class UserInfoServiceImpl implements UserInfoService{
	
	private static final Logger log = LoggerFactory.getLogger(UserInfoServiceImpl.class);
	
	private static final String redis_token_prefix = "_new";

	@Resource
	private UserInfoMapper userInfoMapper;
	
	@Resource
	private VosService vosService;
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private SmsLogService smsLogService;
	
	@Resource
	private ConfigSystemCache configSystemCache;
	
	@Resource
	private TaskIntegralService taskIntegralService;
	
	@Resource
	private TaskLogService taskLogService;
	
	@Resource
	private ConsumeLogService consumeLogService;
	
	@Resource
	private SupportMccService supportMccService;
	
	@Resource
	private OpLogService opLogService;
	
	@Resource
	private LoginLogService loginLogService;
	
	@Resource
	private RedisCacheUtil redisCache;
	
	
	private int getFindXaidMacUser(String xaid,String mac) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("xaid", xaid);
		params.put("mac", mac);
		UserInfo user = userInfoMapper.findByXaidMccAccount(params);
		if (user!=null) {
			return 1;
		}
		return 0;
	}
	
	private Result configAutoLoginResult() {
		String auto_login = configSystemCache.get(Const.SYSTEM_AUTO_LOGIN);
		if (!StringUtil.isEmpty(auto_login)) {
			
			if(auto_login.equals("1")){ //可以自动注册
				
			}else if(auto_login.equals("2")){ //使用fb注册
				return new Result(ResultEnum.ALLOW_FB_REGISTER);
			}else if(auto_login.equals("3")){//使用手机+验证码
				return new Result(ResultEnum.ALLOW_PHONE_VCODE_REGISTER);
			}else if(auto_login.equals("4")){//不允许注册
				return new Result(ResultEnum.NOT_ALLOW_REGISTER);
			}
			
		}
		return null;
	}
	
	/**
	 * 自动登录(xaid+mac)
	 * @param entity
	 * @return
	 */
	public Result autoLogin(UserInfo entity,String vcode,String v){
		
		try {
			
			SupportRegister supportRegister=supportMccService.handlerSupportRegister(entity.getIp(), vcode);
			
			//1.是否支持注册
			if (!supportRegister.isSupport()) {
				log.info("当前所在区不支持注册");
				//写日志
				opLogService.loginWriteLog(supportRegister,"auto login",v,entity.getIp());
				return new Result(ResultEnum.REGISTER_MCC_ERROR);
			}
			
			//判断辅助表是否登录过
			if (loginLogService.getFindByXaidMacCount(entity.getXaid(), entity.getMac())>0) { //已登录过
				
			}else if(getFindXaidMacUser(entity.getXaid(), entity.getMac())>0){ //判断帐户表是否存在
				
			}
			else if(loginLogService.getFindByIpCount(entity.getIp())>3){ //判断ip是否已存在了,非法登录(同一ip最多只能登录3次)
				return new Result(ResultEnum.LOGIN_EXCEPTION);
			}
			
			
			if (!StringUtil.isEmpty(entity.getMcc())) {
				String eMcc = entity.getMcc().replaceAll("[^0-9]+", "");
				entity.setMcc(eMcc);
			}
			
			//2.动态配置注册
			Result rs = configAutoLoginResult();
			if (rs!=null) {
				return rs;
			}
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("xaid", entity.getXaid());
			params.put("mac", entity.getMac());
			UserInfo user = userInfoMapper.findByXaidMccAccount(params);
			
			Map<String, Object> rsMap = new HashMap<String, Object>();
			if (user!=null) { //帐户已存在
				if(user.getStatus().equals(Const.N)){//帐户被冻结
					return new Result(ResultEnum.USER_FROZEN);
				}
				
				 if(user.getTokenExpired().compareTo(new Date()) <= 0){//token过期则更新token
					 
					 RedisToken redisToken=getRedisToken(user.getId(), user.getToken());
					 user.setToken(redisToken.getToken());
					 user.setTokenExpired(redisToken.getTokenExpired());
				 }
				 
				//添加登录记录
				loginLogService.addLoginLogRecord(user.getXaid(), user.getMac(), entity.getIp(),"autoLogin");
				
				rsMap.put("uid", user.getId());
				rsMap.put("token", user.getToken());
				rsMap.put("token_expried", user.getTokenExpired());
				rsMap.put("phone", user.getPhone());
				rsMap.put("name", user.getName());
				rsMap.put("photo", user.getPhoto());
				rsMap.put("mcc", user.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				return new Result(rsMap);
			}
			
			
			
			
			//String token = StringUtil.buildRandomToken(64);
			//entity.setToken(token);
			//entity.setTokenExpired(DateUtil.addMonth(new Date(), 1));
			entity.setStatus(Const.Y);
			entity.setCtime(new Date());
			entity.setMtime(new Date());
			
			if(userInfoMapper.insert(entity) >0){
				
				//redis token
				RedisToken redisToken=getRedisToken(entity.getId(), null);
				entity.setToken(redisToken.getToken());
				entity.setTokenExpired(redisToken.getTokenExpired());
				
				//添加登录记录
				loginLogService.addLoginLogRecord(entity.getXaid(), entity.getMac(), entity.getIp(),"autoLogin");
				
				log.info("新增用户成功");
				rsMap.put("uid", entity.getId());
				rsMap.put("token", entity.getToken());
				rsMap.put("token_expried", entity.getTokenExpired());
				rsMap.put("phone", entity.getPhone());
				rsMap.put("name", entity.getName());
				rsMap.put("photo", entity.getPhoto());
				rsMap.put("mcc", entity.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				//首次注册积分赠送
				StringBuilder sbInteBuilder = new StringBuilder("");
				consumeLogService.addCategoryConsumeLog(Const.SUPPORT_CATEGORY_FIRST_REGISTER, entity.getIp(), entity.getId(), Const.SUPPORT_CATEGORY_FIRST_REGISTER, true, null,sbInteBuilder);
				
				if (sbInteBuilder.length() >0) {
					rsMap.put("integral", sbInteBuilder.toString());
				}
				
				/**
				if(!userAccountService.addAccount(entity.getId())){
					//首次积分赠送
					throw new CommonException(ResultEnum.SYSTEM_ERROR);
				}
				***/
				return new Result(rsMap);
			}else{
				log.error("新增用户失败");
				return new Result(ResultEnum.FAILED);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("自动登录用户发生异常");
			return new Result(ResultEnum.SYSTEM_ERROR);
		}
		
		
	}
	
	
	/***
	 * facebook用户授权登录
	 * @param entity 用户对象
	 * @param vcode  验证码
	 * @return
	 */
	@Transactional
	@Override
	public Result userFbLogin(UserInfo entity,String vcode,String v,String loginType){
		
		try {
			
			
			//1.是否支持注册
			SupportRegister supportRegister=supportMccService.handlerSupportRegister(entity.getIp(), "");
			if (!supportRegister.isSupport()) {
				log.info("当前所在区不支持注册");
				//写日志
				if (!StringUtil.isEmpty(vcode)) {
					opLogService.loginWriteLog(supportRegister,"sms login",v,entity.getIp());
				}else {
					opLogService.loginWriteLog(supportRegister,"fb login",v,entity.getIp());
				}
				return new Result(ResultEnum.REGISTER_MCC_ERROR);
			}
			
			
			//2.判断帐户是否存在
			UserInfo userInfo = userInfoMapper.findByPhoneAccount(entity.getPhone());
			if (userInfo == null) { //fb登录
                if (entity.getXaid()!=null && !StringUtil.isEmpty(entity.getXaid()) && entity.getMac()!=null && !StringUtil.isEmpty(entity.getMac())) {
					
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("xaid", entity.getXaid());
					params.put("mac", entity.getMac());
					userInfo = userInfoMapper.findByXaidMccAccount(params);
				}
			}
			
			Map<String, Object> rsMap = new HashMap<String, Object>();
			if(userInfo!=null){
				
				if(userInfo.getStatus().equals(Const.N)){//帐户被冻结
					return new Result(ResultEnum.USER_FROZEN);
				}

				//3.更新数据
				UserInfo updateUserInfo = new UserInfo();
				updateUserInfo.setId(userInfo.getId());
				if (entity.getPhone()!=null) {
					updateUserInfo.setPhone(entity.getPhone());
				}
				if (entity.getName()!=null) {
					updateUserInfo.setName(entity.getName());
				}
				if (entity.getPhone()!=null) {
					updateUserInfo.setPhone(entity.getPhone());
				}
				if (entity.getFbId()!=null) {
					updateUserInfo.setFbId(entity.getFbId());
				}
				updateUserInfo.setMtime(new Date());
				if (userInfoMapper.update(updateUserInfo)>0) {
					userInfo = userInfoMapper.get(updateUserInfo.getId()); //重新获取最新数据
					log.info("更新数据用户成功");
				}else {
					log.error("更新数据用户失败");
					return new Result(ResultEnum.TOKEN_UPDATE_FAILED);
				}
				
				
				
				//4.更新token
				if(userInfo.getTokenExpired().compareTo(new Date()) <= 0){//token过期则更新token
					
					RedisToken redisToken=getRedisToken(userInfo.getId(), userInfo.getToken());
					userInfo.setToken(redisToken.getToken());
					userInfo.setTokenExpired(redisToken.getTokenExpired());
				}
				
				//添加登录记录
				loginLogService.addLoginLogPhoneRecord(entity.getXaid(), entity.getMac(), entity.getIp(),entity.getPhone(),loginType);
				
				rsMap.put("uid", userInfo.getId());
				rsMap.put("token", userInfo.getToken());
				rsMap.put("token_expried", userInfo.getTokenExpired());
				rsMap.put("phone", userInfo.getPhone());
				rsMap.put("name", userInfo.getName());
				rsMap.put("photo", userInfo.getPhoto());
				rsMap.put("mcc", userInfo.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				return new Result(rsMap);
			}
			
			//String token = StringUtil.buildRandomToken(64);
			//entity.setTokenExpired(DateUtil.addMonth(new Date(), 1));
			//entity.setToken(token);
			entity.setStatus(Const.Y);
			entity.setCtime(new Date());
			entity.setMtime(new Date());
			
			if(userInfoMapper.insert(entity) >0){
				
				RedisToken redisToken=getRedisToken(entity.getId(), null);
				entity.setToken(redisToken.getToken());
				entity.setTokenExpired(redisToken.getTokenExpired());
				
				//添加登录记录
				loginLogService.addLoginLogPhoneRecord(entity.getXaid(), entity.getMac(), entity.getIp(),entity.getPhone(),loginType);
				
				log.info("新增用户成功");
				rsMap.put("uid", entity.getId());
				rsMap.put("token", entity.getToken());
				rsMap.put("token_expried", entity.getTokenExpired());
				rsMap.put("phone", entity.getPhone());
				rsMap.put("name", entity.getName());
				rsMap.put("photo", entity.getPhoto());
				rsMap.put("mcc", entity.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				//首次注册积分赠送
				StringBuilder sbInteBuilder = new StringBuilder("");
				consumeLogService.addCategoryConsumeLog(Const.SUPPORT_CATEGORY_FIRST_REGISTER, entity.getIp(), entity.getId(), "gift", true, null,sbInteBuilder);
				
				if (sbInteBuilder.length() >0) {
					rsMap.put("integral", sbInteBuilder.toString());
				}
				
				if (!StringUtil.isEmpty(entity.getPhone())) { //手机号码不为空,赠送积分
					
					//首次绑定手机号码赠送积分
					if(consumeLogService.addCategoryConsumeLog(Const.TASK_BIND_PHONE, entity.getIp(), entity.getId(), "bind phone", true, null, sbInteBuilder)){
						log.info("首次绑定手机号码赠送积分成功");
					}
				}
				return new Result(rsMap);
			}else{
				log.error("新增用户失败");
				return new Result(ResultEnum.FAILED);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("新增用户发生异常");
			return new Result(ResultEnum.SYSTEM_ERROR);
		}
		
		
		
	}
	
	private boolean isExistsPhone(String phone) {
		UserInfo userInfo = userInfoMapper.findByPhoneAccount(phone);
		if (userInfo != null) { //手机号码不存在
			
		    return true;
			
		}
		return false;
	}
	
	//手机号+验证码登录
	@Override
	public	Result userSMSLogin(UserInfo user,String vcode,String v){
		

		if (loginLogService.getFindByPhoneCount(user.getPhone())>0 || isExistsPhone(user.getPhone())) {
			return this.phoneSmsLogin(user, vcode,v,"smsLogin");
		}else{
            //限制一个ip最多只能登录3次
			if (loginLogService.getFindByIpCount(user.getIp())>3) {
				log.error("sms login ip已登录过");
				return new Result(ResultEnum.LOGIN_EXCEPTION);
			}
		}
		return this.phoneSmsLogin(user, vcode,v,"smsLogin");
		
	}
	
	private Result phoneSmsLogin(UserInfo entity,String vcode,String v,String loginType) {
		
    try {
			
			
			//1.是否支持注册
			SupportRegister supportRegister=supportMccService.handlerSupportRegister(entity.getIp(), "");
			if (!supportRegister.isSupport()) {
				log.info("当前所在区不支持注册");
				//写日志
				if (!StringUtil.isEmpty(vcode)) {
					opLogService.loginWriteLog(supportRegister,"sms login",v,entity.getIp());
				}else {
					opLogService.loginWriteLog(supportRegister,"fb login",v,entity.getIp());
				}
				return new Result(ResultEnum.REGISTER_MCC_ERROR);
			}
			
			//2.证码短信验码是否正常
			StringBuilder smsSending = new StringBuilder();
			if(!smsLogService.smsVerify(entity.getPhone(),vcode, Const.SMS_TYPE_LOGIN,smsSending)){
				if (smsSending.toString().trim().equals(Const.SMS_SENDING)) {
					return new Result(ResultEnum.SMS_SENDING_ERROR);
				}
				return new Result(ResultEnum.SMS_INVALID);
			}
			
			//3.查询帐号是否存在
			UserInfo userInfo = userInfoMapper.findByPhoneAccount(entity.getPhone());
			if (userInfo == null) { 
                if (entity.getXaid()!=null&& !StringUtil.isEmpty(entity.getXaid()) && entity.getMac()!=null && !StringUtil.isEmpty(entity.getMac())) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("xaid", entity.getXaid());
					params.put("mac", entity.getMac());
					userInfo = userInfoMapper.findByXaidMccAccount(params);
				}
			}
			
			Map<String, Object> rsMap = new HashMap<String, Object>();
			if(userInfo!=null){
				
				if(userInfo.getStatus().equals(Const.N)){//帐户被冻结
					return new Result(ResultEnum.USER_FROZEN);
				}
				
				//更新token
				if(userInfo.getTokenExpired().compareTo(new Date()) <= 0){//token过期则更新token
					
					RedisToken redisToken=getRedisToken(userInfo.getId(), userInfo.getToken());
					userInfo.setToken(redisToken.getToken());
					userInfo.setTokenExpired(redisToken.getTokenExpired());
				}
				
				//添加登录记录
				loginLogService.addLoginLogPhoneRecord(entity.getXaid(), entity.getMac(), entity.getIp(),entity.getPhone(),loginType);
				
				rsMap.put("uid", userInfo.getId());
				rsMap.put("token", userInfo.getToken());
				rsMap.put("token_expried", userInfo.getTokenExpired());
				rsMap.put("phone", userInfo.getPhone());
				rsMap.put("name", userInfo.getName());
				rsMap.put("photo", userInfo.getPhoto());
				rsMap.put("mcc", userInfo.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				return new Result(rsMap);
			}
			
			
			
			//String token = StringUtil.buildRandomToken(64);
			//entity.setTokenExpired(DateUtil.addMonth(new Date(), 1));
			//entity.setToken(token);
			entity.setStatus(Const.Y);
			entity.setCtime(new Date());
			entity.setMtime(new Date());
			
			if(userInfoMapper.insert(entity) >0){
				
				RedisToken redisToken=getRedisToken(entity.getId(), null);
				entity.setToken(redisToken.getToken());
				entity.setTokenExpired(redisToken.getTokenExpired());
				
				//添加登录记录
				loginLogService.addLoginLogPhoneRecord(entity.getXaid(), entity.getMac(), entity.getIp(),entity.getPhone(),loginType);
				
				log.info("新增用户成功");
				rsMap.put("uid", entity.getId());
				rsMap.put("token", entity.getToken());
				rsMap.put("token_expried", entity.getTokenExpired());
				rsMap.put("phone", entity.getPhone());
				rsMap.put("name", entity.getName());
				rsMap.put("photo", entity.getPhoto());
				rsMap.put("mcc", entity.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				//首次注册积分赠送
				StringBuilder sbInteBuilder = new StringBuilder("");
				consumeLogService.addCategoryConsumeLog(Const.SUPPORT_CATEGORY_FIRST_REGISTER, entity.getIp(), entity.getId(), "gift", true, null,sbInteBuilder);
				
				if (sbInteBuilder.length() >0) {
					rsMap.put("integral", sbInteBuilder.toString());
				}
				
				if (!StringUtil.isEmpty(entity.getPhone())) { //手机号码不为空,赠送积分
					
					//首次绑定手机号码赠送积分
					if(consumeLogService.addCategoryConsumeLog(Const.TASK_BIND_PHONE, entity.getIp(), entity.getId(), "bind phone", true, null, sbInteBuilder)){
						log.info("首次绑定手机号码赠送积分成功");
					}
				}
				return new Result(rsMap);
			}else{
				log.error("新增用户失败");
				return new Result(ResultEnum.FAILED);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("新增用户发生异常");
			return new Result(ResultEnum.SYSTEM_ERROR);
		}
		
	}
	
	
	/***
	 * 使用帐户与密码登录
	 * @param phone  手机号
	 * @param pwd    密码
	 * @return
	 */
	@Override
	public Result userAccountLogin(String phone,String pwd,String ip,String v,String xaid,String mac){
		

		//1.是否支持注册
		SupportRegister supportRegister=supportMccService.handlerSupportRegister(ip, "");
		if (!supportRegister.isSupport()) {
			log.info("当前所在区不支持注册");
			//写日志
			opLogService.loginWriteLog(supportRegister,"account and pwd login",v,ip);
			return new Result(ResultEnum.REGISTER_MCC_ERROR);
		}
		
		
		UserInfo userInfo = userInfoMapper.queryForPhone(phone);
		if (userInfo ==null) {
			log.info("登录时，未找到用户phone={}",phone);
			return new Result(ResultEnum.USER_NOT_EXIST);
		}
		if(userInfo.getStatus().equals(Const.N)){//帐户被冻结
			return new Result(ResultEnum.USER_FROZEN);
		}
		String md5pwd = MD5Util.md5Hex(pwd);
		if(!md5pwd.equals(userInfo.getPassword())){
			log.info("登录时，密码错误phone={}",phone);
			return new Result(ResultEnum.USER_PASSWORD_ERROR);
		}
		
		/***
		if (!StringUtil.isEmpty(xaid)&&!StringUtil.isEmpty(mac)) {
			
			if (updateXaidMac(userInfo.getId(), xaid, mac)) {
				userInfo = userInfoMapper.get(userInfo.getId());
			}else{
				
				return new Result(ResultEnum.FAILED);
			}
			
		}
		***/
		
		if(userInfo.getTokenExpired().compareTo(new Date()) <= 0){//token过期则更新token
			
			RedisToken redisToken=getRedisToken(userInfo.getId(), userInfo.getToken());
			userInfo.setToken(redisToken.getToken());
			userInfo.setTokenExpired(redisToken.getTokenExpired());
		}
	
		//添加登录记录
		loginLogService.addLoginLogPhoneRecord(xaid, mac, ip,userInfo.getPhone(),"accountLogin");
		
		
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("uid", userInfo.getId());
		rsMap.put("token", userInfo.getToken());
		rsMap.put("token_expried", userInfo.getTokenExpired());
		rsMap.put("phone", userInfo.getPhone());
		rsMap.put("name", userInfo.getName());
		rsMap.put("photo", userInfo.getPhoto());
		rsMap.put("mcc", userInfo.getMcc());
		rsMap.put("areacode", supportRegister.getIsoCode());
		return new Result(rsMap);
	}
	
	@Override
	public Result settingPassword(Integer id,String pwd){
		
		UserInfo userInfo = userInfoMapper.get(id);
		if(userInfo==null){
			return new Result(ResultEnum.USER_NOT_EXIST);
		}
		
		UserInfo entity=new UserInfo();
		entity.setId(id);
		String md5pwd = MD5Util.md5Hex(pwd);
		entity.setPassword(md5pwd);
		if(userInfoMapper.update(entity)>0){
			log.info("修改密码成功");
			return new Result();
		}
		log.error("修改密码失败");
		return new Result(ResultEnum.FAILED);
	}
	
	//绑定手机
	@Override
	public	Result bindPhone(Integer id,String phone,String vcode,String ip,String xaid,String mac){
		
		
		/***
		//表示当前手机号码不支持注册区域
		if (supportMccService.getSupportLoginBindPhoneCount(phone.replaceAll("^00", "")) == 0) { 
			return new Result(ResultEnum.REGISTER_MCC_ERROR);
		}
		***/

		StringBuilder smsSending = new StringBuilder();
		if(!smsLogService.smsVerify(phone,vcode, Const.SMS_TYPE_BIND_PHONE,smsSending)){
			if (smsSending.toString().trim().equals(Const.SMS_SENDING)) {
				return new Result(ResultEnum.SMS_SENDING_ERROR);
			}
			return new Result(ResultEnum.SMS_INVALID);
		}
		
		SupportRegister supportRegister=supportMccService.handlerSupportRegister(ip, "");
		
		UserInfo userInfo = userInfoMapper.findByPhoneAccount(phone);
		if (userInfo == null) { //不存在，则绑定
			
			userInfo = userInfoMapper.get(id);
			if(userInfo==null){//用户不存在则创建用户
				return new Result(ResultEnum.USER_NOT_EXIST);
			}
			
			UserInfo user = new UserInfo();
			user.setId(id);
			user.setPhone(phone);
			user.setMtime(new Date());
			if(userInfo.getTokenExpired().compareTo(new Date()) <= 0){//token过期则更新token
				
				 RedisToken redisToken=getRedisToken(userInfo.getId(), userInfo.getToken());
				 userInfo.setToken(redisToken.getToken());
				 userInfo.setTokenExpired(redisToken.getTokenExpired());
			}
			userInfo.setPhone(phone);
			StringBuilder sbIntegral = new StringBuilder("");
			if(userInfoMapper.update(user)>0){
				log.info("绑定手机号码成功");
				//绑定手机送积分
				if (consumeLogService.existsBindPhone(id)) {
					log.info("绑定手机已送积分");
				}else {
					
					if (consumeLogService.hasOverMaxIntegralLimit(id)) {
						log.info("绑定手机超过最大积分赠送");
					}else {
						
						if(supportMccService.isSupportCountry(ip)){ //支持注册国家，才送绑定积分
							if(consumeLogService.addCategoryConsumeLog(Const.TASK_BIND_PHONE, ip, id, Const.TASK_BIND_PHONE, true, null, sbIntegral)){
								log.info("积分赠送成功");
							}
						}else{
							log.info("不支持注册国家，绑定手机积分不赠送");
						}
						
					}

				}
				
				//添加登录记录
				loginLogService.addLoginLogPhoneRecord(xaid, mac, ip,userInfo.getPhone(),"bind_phone");
				
				Map<String, Object> rsMap = new HashMap<String, Object>();
				rsMap.put("uid", userInfo.getId());
				rsMap.put("token", userInfo.getToken());
				rsMap.put("token_expried", userInfo.getTokenExpired());
				rsMap.put("phone", userInfo.getPhone());
				rsMap.put("name", userInfo.getName());
				rsMap.put("photo", userInfo.getPhoto());
				rsMap.put("mcc", userInfo.getMcc());
				rsMap.put("areacode", supportRegister.getIsoCode());
				if (sbIntegral.length()>0) {
					rsMap.put("integral", sbIntegral);
				}
				return new Result(rsMap);
				
				
			}else{
				log.error("绑定手机号码失败");
			}
			return new Result(ResultEnum.FAILED);
			
			
			
		}else { //存在，则登录
			
			if(userInfo.getStatus().equals(Const.N)){//帐户被冻结
				return new Result(ResultEnum.USER_FROZEN);
			}
			
			//判断token是否过期
			if(userInfo.getTokenExpired().compareTo(new Date()) <= 0){//token过期则更新token
				//更新token
				 RedisToken redisToken=getRedisToken(userInfo.getId(), userInfo.getToken());
				 userInfo.setToken(redisToken.getToken());
				 userInfo.setTokenExpired(redisToken.getTokenExpired());
			}
		
			//添加登录记录
			loginLogService.addLoginLogPhoneRecord(xaid, mac, ip,userInfo.getPhone(),"bind_phone");
			
			Map<String, Object> rsMap = new HashMap<String, Object>();
			rsMap.put("uid", userInfo.getId());
			rsMap.put("token", userInfo.getToken());
			rsMap.put("token_expried", userInfo.getTokenExpired());
			rsMap.put("phone", userInfo.getPhone());
			rsMap.put("name", userInfo.getName());
			rsMap.put("photo", userInfo.getPhoto());
			rsMap.put("mcc", userInfo.getMcc());
			rsMap.put("areacode", supportRegister.getIsoCode());
			return new Result(rsMap);
		}
	}
	
	//查询用户是否存在
	@Override
	public	Result existsUser(String phone){
		UserInfo userInfo = this.findByPhone(phone);
		if(userInfo == null){
			return new Result(ResultEnum.USER_NOT_EXIST);
		}
		return new Result();
	}
	
	@Override
	public UserInfo getUserForId(Integer uid){
		
		return userInfoMapper.get(uid);
		
	}
	
	//查询用户
	@Override
	public	UserInfo findByPhone(String phone){
		return userInfoMapper.queryForPhone(phone);
	}
	
	/**
	 * 获取7天内没有拨打的记录的话机用户列表
	 * @param icall  话机前缀
	 * @return
	 */
	@Override
	public List<UserInfo> getUnTelephoneList(VosAccount acct){
		
		Date nowDate = new Date();
		Date firstDay = DateUtil.addDate(nowDate, -6);
		
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("billAcc", acct.getBillAccount());
		rsMap.put("icall", acct.getVosPrefix());
		rsMap.put("startTime", DateUtil.getDateTimeString(firstDay, DateUtil.DATE_TIME_FMT));
		rsMap.put("endTime", DateUtil.getDateTimeString(nowDate, DateUtil.DATE_TIME_FMT));
		
		return userInfoMapper.getWeekCallerNotRecordList(rsMap);
	}
	
	//查询帐户信息
	@Override
	public	Result queryUserForXaidMac(String xaid,String mac){
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("xaid", xaid);
		params.put("mac", mac);
		UserInfo user = userInfoMapper.findByXaidMccAccount(params);
		if (user == null) {
			return new Result(ResultEnum.USER_NOT_EXIST);
		}
		Date nowDate = new Date();
		 if(user.getTokenExpired().compareTo(nowDate) < 0){ //token过期重新生成
			 String token = StringUtil.buildRandomToken(64);
				//更新token
				UserInfo updateUser = new UserInfo();
				updateUser.setId(user.getId());
				updateUser.setToken(token);
				updateUser.setTokenExpired(DateUtil.addMonth(new Date(), 1));
				updateUser.setMtime(new Date());
				if(userInfoMapper.update(updateUser)>0){
					user = userInfoMapper.get(updateUser.getId());
					log.info("更新token成功");
				}else{
					log.error("更新token失败");
					return new Result(ResultEnum.TOKEN_UPDATE_FAILED);
				}
		 }
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("uid", user.getId());
		rsMap.put("token", user.getToken());
		rsMap.put("token_expried", user.getTokenExpired());
		rsMap.put("phone", user.getPhone());
		rsMap.put("name", user.getName());
		rsMap.put("photo", user.getPhoto());
		rsMap.put("mcc", user.getMcc());
		return new Result(rsMap);
	}
	
	//修改用户信息
	@Override
	public	Result editUser(UserInfo user){
		
		if (user == null) {
			return new Result(ResultEnum.FAILED);
		}
		if (userInfoMapper.update(user) > 0) {
			return new Result();
		}
		return new Result(ResultEnum.FAILED);
	}
	
	//请求验证
	@Override
	public	ResultEnum requestVerify(String uid,String token) {
		
        if (token.endsWith(redis_token_prefix)) { //表示redis token验证
        	
        	//token过期
			if (!redisCache.verifyToken(Integer.valueOf(uid), token.replaceAll(redis_token_prefix+"$", ""))) {
				return ResultEnum.TOKEN_EXPRIED;
			}
		}else {
			
				String existsOldToken = redisCache.get(token);
				if (!StringUtil.isEmpty(existsOldToken)) {
					//token过期
					if (!redisCache.verifyTokenValue(Integer.valueOf(uid),existsOldToken)) {
						return ResultEnum.TOKEN_EXPRIED;
					}
					
				}else {
					UserInfo user = getUserForId(Integer.valueOf(uid));
			        //1.帐户不存在
			        if(user == null){ 
			        	return ResultEnum.USER_ILLEGAL;
			        }
			        
			       //2.帐户被冻结
			        if (user.getStatus().equals(Const.N)) { 
			        	return ResultEnum.USER_FROZEN;
					}
			        
			        //3.token错误
			        if (!token.equals(user.getToken())) {
			        	return ResultEnum.TOKEN_INVALID;
					}
			        
			        //4.token过期
			        Date nowDate = new Date();
			        if(user.getTokenExpired().compareTo(nowDate) < 0){
			        	return ResultEnum.TOKEN_EXPRIED;
			        }
			        
			        //原来没有保存token
			        RedisToken redisToken = new RedisToken();
			        redisToken.setId(user.getId());
			        redisToken.setToken(user.getToken());
			        redisToken.setTokenExpired(user.getTokenExpired());
			        redisCache.setRedisToken(redisToken);
			        
				}
			
			   
		        
		        
		}
        return null;
       
	}
	
	
	//更新xaid与mac
	private boolean updateXaidMac(Integer id,String xaid,String mac) {
		UserInfo updateUser = new UserInfo();
		updateUser.setId(id);
		updateUser.setXaid(xaid);
		updateUser.setMac(mac);
		updateUser.setMtime(new Date());
		if(userInfoMapper.update(updateUser)>0){
			return true;
		}else{
			return false;
		}
	}
	
	/***
	//更新token
	private boolean updateToken(Integer id) {
		String token = StringUtil.buildRandomToken(64);
		//更新token
		UserInfo updateUser = new UserInfo();
		updateUser.setId(id);
		updateUser.setToken(token);
		updateUser.setTokenExpired(DateUtil.addMonth(new Date(), 1));
		updateUser.setMtime(new Date());
		if(userInfoMapper.update(updateUser)>0){
			return true;
		}else{
			return false;
		}
	}
	**/
	
	//redis token更新
	private RedisToken getRedisToken(Integer uid,String oldToken) {
		
		
		RedisToken entity = new RedisToken(uid);
		//缓存token
		redisCache.setRedisToken(entity);
		
		//删除旧token
		if (!StringUtil.isEmpty(oldToken)) {
			redisCache.del(oldToken);
		}
		
		//数据库更新token
		UserInfo updateUser = new UserInfo();
		updateUser.setId(entity.getId());
		updateUser.setToken(entity.getToken());
		updateUser.setTokenExpired(entity.getTokenExpired());
		updateUser.setMtime(new Date());
		userInfoMapper.update(updateUser);
		
		//String redis_token = entity.getToken();
		//entity.setToken(redis_token);
		
        return entity;
	}
	
}
